library(GGally)
library(ggplot2)
library(dplyr)
load("compare_df.RData")


############ Figure 1

my_custom_cor <- function(data, mapping, color = I("grey50"), ...) {
  
  # get the x and y data to use the other code
  x <- GGally::eval_data_col(data, mapping$x)
  y <- GGally::eval_data_col(data, mapping$y)
  
  # Old:
  #x <- eval(mapping$x, data)
  #y <- eval(mapping$y, data)
  
  ct <- cor.test(x,y)
  
  r <- unname(ct$estimate)
  rt <- format(r, digits=2)[1]
  
  # plot the cor value
  ggally_text(
    label = as.character(rt), 
    mapping = aes(),
    xP = 0.5, yP = 0.5, 
    size = 3,
    color = color,
    ...
  ) + 
    # remove all the background stuff and wrap it with a dashed line
    theme_classic() + 
    theme(
      # panel.background = element_rect(
      #   color = color, 
      #   linetype = "longdash"
      # ), 
      axis.line = element_blank(), 
      axis.ticks = element_blank(), 
      axis.text.y = element_blank(), 
      axis.text.x = element_blank()
    )
}


my_custom_smooth <- function(data, mapping, ...) {
  ggplot(data = data, mapping = mapping) +
    # geom_jitter(color = '#8da0cb', size = 0.00001) + 
    geom_smooth(method = "gam", color = 'black', se = TRUE, level = 0.9, lwd = .5, ...) +
    #coord_cartesian(ylim = c(0, 1)) +
    theme_minimal() #+
  #scale_y_continuous(breaks = c(0, .5, 1)) +
  # scale_x_continuous(breaks = c(0, .5, 1)) 
}

my_custom_density <- function(data, mapping, ...) {
  ggplot(data = data, mapping = mapping) +
    geom_histogram(color = '#8da0cb') + 
    theme_minimal() #+
  #coord_cartesian(ylim = c(0, 4)) +
  # scale_x_continuous(breaks = c(0, .5, 1)) +
  # scale_y_continuous(breaks = c(0, 4, 4)) 
}





p <- ggpairs(subset(compare_df, select = c(taub,
                                           srsvas,
                                           IdealPointDistance,
                                           latent_score_gdelt,
                                           latent_score)),
             lower = list(continuous = my_custom_smooth),
             diag = list(continuous = my_custom_density),
             upper = list(continuous = my_custom_cor),
             columnLabels = c("taub" = "Tau-b", 
                              "srsvas" = "S-Scores",
                              "IdealPointDistance" = "Ideal Point",
                              "latent_score_gdelt" = "GDELT",
                              "latent_score" = "ICEWS")) 

p+  theme(axis.text.y = element_text(size = 12),
          axis.text.x = element_text(size = 12),
          panel.background  = element_blank(),
          panel.border      = element_blank(),
          strip.background  = element_blank(),
          plot.background = element_blank(),
          text = element_text(size = 14)
)

ggsave("./Tex/paireplot.png", width = 8.5, height = 6)


normalize <- function(x, na.rm = TRUE) {
  return((x- min(x)) /(max(x)-min(x)))
}

# df2 <- compare_df %>% dplyr::select(taub,
#                                     srsvas,
#                                     IdealPointDistance,
#                                     latent_score_gdelt,
#                                     latent_score)
# 
# df2 <- df2 %>% dplyr::mutate_at(vars(IdealPointDistance:latent_score), ~normalize(.))
# 
# p <- ggpairs(subset(df2, select = c(taub,
#                                     srsvas,
#                                     IdealPointDistance,
#                                     latent_score_gdelt,
#                                     latent_score)),
#              lower = list(continuous = my_custom_smooth),
#              diag = list(continuous = my_custom_density),
#              upper = list(continuous = my_custom_cor),
#              columnLabels = c("taub" = "Tau-b", 
#                               "srsvas" = "S-Scores",
#                               "IdealPointDistance" = "Ideal Point",
#                               "latent_score_gdelt" = "GDELT",
#                               "latent_score" = "ICEWS")) 
# 
# p+  theme(axis.text.y = element_text(size = 12),
#           axis.text.x = element_text(size = 12),
#           panel.background  = element_blank(),
#           panel.border      = element_blank(),
#           strip.background  = element_blank(),
#           plot.background = element_blank(),
#           text = element_text(size = 14)
# )
# 
# ggsave("./Tex/paireplot2.png", width = 8.5, height = 6)
# 

############ Figure 2

load("comparing.plots.RData")

com_df <- bind_rows(df_AUS, df_FRA, df_GBR, df_GER, df_IDN, df_IND,
                    df_JPN, df_KOR, df_PAK, df_RUS, df_USA, df_VNM)

com_df <- com_df %>% dplyr::select(time, state_name,
                                   idealdist_chn,  latent_gdeltchn, latent_icewschn,thu_score)

library(tidyr)
library(ggpubr)

com_df_long <- pivot_longer(com_df, cols =idealdist_chn:thu_score,
                            values_to = "Scores")


unique(com_df_long$state_name)
states <- c("United States", "Japan",  "India","Russia" )

library(ggthemes)
com_df_long2 <- com_df_long %>% dplyr::filter(state_name %in% states)

states_names <- c(
  "idealdist_chn" = "理想点分值",
  "latent_gdeltchn" = "GDELT",
  "latent_icewschn" = "ICEWS",
  "thu_score" = "清华分值"
)


com_df_long2$time <- as.Date(com_df_long2$time )
ggplot(data = com_df_long2, aes(x = time, y = Scores, linetype= state_name, color =state_name))+
  geom_line(linewidth = 1) + 
  facet_wrap(~name, scales = "free_y", nrow = 4, labeller = as_labeller(states_names))+
  theme_pubclean()+
  labs(x = "年份", y = "")+
  scale_x_date(date_breaks = "4 years", date_labels = "%Y")+
  scale_linetype_manual(name="", values = c("twodash","dotted","dashed","solid"),
                        labels = c("印度","日本", "俄罗斯", "美国"))+
  scale_color_manual(name="", values = c("black","blue","red","gray"),
                     labels = c("印度","日本", "俄罗斯", "美国"))+
  theme(legend.position = "bottom",
        legend.title=element_blank(),
        legend.text = element_text(colour="blue", size=16),
        axis.text= element_text(size=16),
        text = element_text(size=16, family = 'KaiTi'),
        plot.title = element_text(hjust = .5, size = 16))
ggsave("./Tex/compare.pdf", width =8, height = 6, units = "in")

